import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository,Like } from 'typeorm';
import { Categories } from './categories.entity';
@Injectable()
export class CategoriesService {
    constructor(
        @InjectRepository(Categories)
        private readonly categoryRepository: Repository<Categories>,
    ) { }
    async findAll(info: any): Promise<Categories[]> {
        return await this.categoryRepository.findBy({ merchant_id: In(info.merchant_ids),...info });
    }
    async findOne(id: number): Promise<Categories | null> {
        return await this.categoryRepository.findOneBy({ id });
    }
    async create(category: Categories): Promise<Categories> {
        return await this.categoryRepository.save(category);
    }
    async update(id: number, category: Categories): Promise<any> {
        try {
            const categorys = await this.categoryRepository.findBy({ name:category.name });
            if(categorys.length>0){
                return { msg: '分类名称重复' };
            }
            return await this.categoryRepository.update(id, category);
        } catch (error) {
            return { msg: '更新失败' };
        }

    }
    async delete(id: number): Promise<any> {
        try {
            return await this.categoryRepository.delete(id);
        } catch (error) {
            return { msg: '删除失败' };
        }
    }
    async findBy(info: any): Promise<any> {
        // 校验输入参数
        if (!Array.isArray(info.merchant_id) || info.merchant_id.some((id: number) => typeof id !== 'number')) {
            throw new Error('Invalid merchant_id: must be an array of numbers');
        }

        if (typeof info.pageSize !== 'number' || info.page < 1 || info.pageSize < 1) {
            throw new Error('Invalid pagination parameters: page and pageSize must be positive numbers');
        }
        let data = JSON.parse(JSON.stringify(info));
        delete data.merchant_id;
        delete data.page;
        delete data.pageSize;
        // 构建查询条件
        let whereConditions: any = {
            merchant_id: In(info.merchant_id),
        };

        if (data.name) {
            whereConditions.name = Like(`%${data.name}%`);
            delete data.name;
        }

        whereConditions = { ...whereConditions, ...data };
        try {
            const [posts, total] = await this.categoryRepository.findAndCount({
              where: whereConditions,
              skip: (info.page - 1) * info.pageSize,
              order: {
                sort_order: 'asc',
              },
              take: info.pageSize,
            });
        
            return {
              data: posts,
              total,
              page: info.page,
              pageSize: info.pageSize,
              // ...其他分页信息
            };
          } catch (error) {
            throw new Error('Failed to fetch dishes');
          }
    }
}
